package com.fingersoft.im.ui.home

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.content.res.Resources
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.Typeface
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.util.Log.e
import android.util.Log.w
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.*
import androidx.annotation.DrawableRes
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.view.menu.MenuBuilder
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.lifecycle.lifecycleScope
import cn.fingersoft.android.content.checkLandscape
import cn.fingersoft.android.content.requestedOrientationByScreenOriginationConfig
import cn.fingersoft.common.theme.CommonTheme
import cn.fingersoft.feature.ui.components.UIStatusBar
import cn.fingersoft.feature.ui.components.UITabBar
import cn.fingersoft.im.common.navigation.NavigationHostManager
import cn.fingersoft.im.common.navigation.WrapActivityNavigationHost
import cn.fingersoft.im.feature.home.HomeTabSwitchEvent
import cn.fingersoft.util.BuildConfigUtil
import cn.fingersoft.util.weakReference
import com.fingersoft.badger.AppBadgerManager
import com.fingersoft.business.BusinessContext
import com.fingersoft.business.BusinessContext.Companion.enterpriseConfigProvider
import com.fingersoft.business.contact.IContactChooseCallback
import com.fingersoft.business.contact.IContactProvider
import com.fingersoft.business.im.api.JoinGroupData
import com.fingersoft.business.router.start
import com.fingersoft.business.theme.ThemeChangedEvent
import com.fingersoft.common.CommonContext
import com.fingersoft.common.ICallback
import com.fingersoft.cycle.ActivityCycleManager
import com.fingersoft.cycle.ActivityCycleManager.Companion.onCreate
import com.fingersoft.cycle.IActivityCycle
import com.fingersoft.feature.filemanager.SealFileManagerContext
import com.fingersoft.feature.login.LoginActivityCycle
import com.fingersoft.feature.newlock.LockActivityCycle
import com.fingersoft.feature.sensitiveword.SensitiveWordContext
import com.fingersoft.feature.sensitiveword.dao.SensitiveWordDaoUtils
import com.fingersoft.feature.webview.CordovaWebViewFragment
import com.fingersoft.feature.webview.util.AndroidBug5497Workaround
import com.fingersoft.im.MyApplication2.Companion.getMainHandler
import com.fingersoft.im.R
import com.fingersoft.im.api.base.BaseModelCallback2
import com.fingersoft.im.base.ImmersiveBaseActivity
import com.fingersoft.im.base.MyActivityManager
import com.fingersoft.im.common.databinding.LayoutBaseBinding
import com.fingersoft.im.common.intent.IntentQueue
import com.fingersoft.im.crash.CrashHelper
import com.fingersoft.im.databinding.ActivityMainBinding
import com.fingersoft.im.databinding.LayoutTopBinding
import com.fingersoft.im.event.EventManager
import com.fingersoft.im.event.PluginsEventManager
import com.fingersoft.im.model.BadgerResponse
import com.fingersoft.im.utils.*
import com.fingersoft.im.utils.AppConfigUtils.Companion.getAppConfigInfo
import com.fingersoft.im.utils.AppUtils.useGnet
import com.fingersoft.im.utils.AppUtils.useGnetInIMMenu
import com.fingersoft.im.view.DragPointView
import com.fingersoft.im.view.LoadDialog
import com.fingersoft.im.view.SwappableViewPager
import com.fingersoft.image.ImageUtils
import com.fingersoft.image.SkxDrawableHelper
import com.fingersoft.plugins.scancode.zxing.activity.CustomCaptureActivity
import com.fingersoft.stomp.AppLaunch
import com.fingersoft.stomp.MyStompClient
import com.fingersoft.tab.IOnCountChangeListener
import com.fingersoft.tab.ITabFragment
import com.fingersoft.tab.ITabFragment2
import com.fingersoft.tab.TabFragmentManager
import com.fingersoft.theme.ThemeM
import com.fingersoft.ui.createStatusBarView
import com.fingersoft.ui.getStatusBarHeight
import com.fingersoft.ui.main.ITabHost
import com.fingersoft.util.AppEventType
import com.fingersoft.util.AppEventUtil
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.kareluo.ui.OptionMenu
import me.kareluo.ui.OptionMenuView
import me.kareluo.ui.PopupMenuView
import okhttp3.Call
import okhttp3.Response
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONException
import org.json.JSONObject
import java.lang.reflect.Method
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.set


/**ui1 & ui2*/
open class MainBaseActivity : ImmersiveBaseActivity(), ITabHost, androidx.viewpager.widget.ViewPager.OnPageChangeListener, View.OnClickListener, OptionMenuView.OnOptionMenuClickListener {
    override fun onPageScrollStateChanged(p0: Int) {
    }

    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
    }

    override fun onPageSelected(position: Int) {
        if (position >= mTabItems.size) return
        val tabItemHolder = mTabItems[position]
        resetTabItems()
        tabItemClick(tabItemHolder)
    }

    private var defaultTabId: Int = 0
    private var mTabItems: ArrayList<TabItemViewHolder> = ArrayList()
    private var currentTabItem: TabItemViewHolder? = null
    private lateinit var navigationHost: WrapActivityNavigationHost
    private var main_cycles: MutableList<IActivityCycle> = ArrayList<IActivityCycle>()
    protected var mViewPager: androidx.viewpager.widget.ViewPager? = null
    protected var mFragment: MutableList<androidx.fragment.app.Fragment> = ArrayList<androidx.fragment.app.Fragment>()

    @Deprecated("使用 CommonTopView 组件，共享的 mTopLayout 在 viewpager 滑动切换时 界面无法对齐")
    private var mTopLayout: View? = null
    private var actionbar_right_img: ImageView? = null
    private var actionbar_main_right_meeting: ImageView? = null
    private var actionbar_main_right_contact: ImageView? = null
    private var actionbar_center_title: TextView? = null

    private var mBottomLayoutMustGone: Boolean? = false

    @Deprecated("use main_bottom")
    internal var mMainBottom: LinearLayout? = null
    private var useColorFilter = false
    private var themeColor: Int = 0
    private var mIsAtHome = true
    private var mOnCreateTime: Long = 0
    private var mCustomMenuView: PopupMenuView? = null
    private var mLayoutStatusBar: View? = null
    private var mLayoutMainContent: View? = null
    private var dragPointView: DragPointView? = null
    private var mExitTime: Long = 0
    protected lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        BusinessContext.tabHost = this
        // 4.4 上statubar使用的是fake，主界面是透明状态栏，自己处理状态栏，所以不需要设置状态栏颜色，即不使用4。4的fake，只是透明状态栏,
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
            notSetStatusBarColor()
            overridePendingTransition(0, 0)
        }
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        binding = ActivityMainBinding.bind(window.decorView.findViewById(R.id.main_container))
        AndroidBug5497Workaround.assistActivity(this)
        mMainBottom = findViewById(R.id.main_bottom)
        dragPointView = findViewById(R.id.seal_num)
        assert(dragPointView != null) { "dragPointView is null" }
        supportActionBar(false)
        mContext = this
        var lockActivityCycle: IActivityCycle? = null
        if (AppUtils.useLock()) {
            lockActivityCycle = LockActivityCycle(null)
        }
        if (AppUtils.useLogin()) {
            main_cycles.add(LoginActivityCycle(lockActivityCycle))
        } else {
            if (lockActivityCycle != null) {
                main_cycles.add(lockActivityCycle)
            }
        }
        for (cycle in main_cycles) {
            cycle.onCreate(this, savedInstanceState)
        }

        SealFileManagerContext.instance.changeUser(this)

        themeColor = BusinessContext.theme.getThemeColor(this)

        mOnCreateTime = System.currentTimeMillis()

        if (AppUtils.isLogged()) {
            //心跳
            MyStompClient.createStompClient(getMainHandler())
        }

        onCreate(CYCLE_GROUP, this, savedInstanceState)
        eventLogAddAndUpload()
        //// TODO: 2019-06-21 此处应该不需要 check ,or remove this line
        enterpriseConfigProvider.applyEnterpriseConfig()

        initViews()
        initMainViewPager()
        //initMainViewPagerEnd();
        navigationHost = WrapActivityNavigationHost(this, R.id.main_right_fragment_container)
        this.requestedOrientationByScreenOriginationConfig(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
        if (this.checkLandscape()) {
            onConfigurationChangedLandscape()
        } else {
            onConfigurationChangedPortrait()
        }
        NavigationHostManager.hosts.add(navigationHost)

        binding.mainViewpager.apply {
            adapter = object : androidx.fragment.app.FragmentPagerAdapter(supportFragmentManager) {
                override fun getItem(position: Int): androidx.fragment.app.Fragment {
                    return mFragment[position]
                }

                override fun getCount(): Int {
                    return mFragment.size
                }

                override fun getItemPosition(`object`: Any): Int {
                    return super.getItemPosition(`object`)
                }

            }
            offscreenPageLimit = 4
            addOnPageChangeListener(this@MainBaseActivity)
        }

        addTabItems()
        defaultTabId = tabItemList.indexOfFirst { it.isHomeDefault }
        parseScheme(intent)
        setDefaultViewPager(defaultTabId, true)
        Handler().postDelayed({
            //延时设置,否则状态栏没法生效
            setDefaultViewPager(defaultTabId, false)
        }, 200)

        BusinessContext.calendarEvent?.queryNewEvents()
        fetchTotalReminder()

        if (BuildConfigUtil.getBoolean("style_bjsw", false)) {
            ContextCompat.getDrawable(this, R.drawable.bjsw_main_bottom_background)?.let {
                this.binding.mainLayoutBottom.mainBottom.background = it
                this.binding.mainLayoutBottom.layoutBottom.background = it
            }
        }

        this.binding.mainLayoutBottom.layoutBottom.visibility = if (BuildConfigUtil.getBoolean("useMainTab", false))
            View.VISIBLE else View.GONE

        if(BuildConfigUtil.getBoolean("crashLogToServer")){
            uploadCrashLog()
        }
    }

    private fun uploadCrashLog() {
        lifecycleScope.launch(Dispatchers.IO) {
            CrashHelper().upload()
        }
    }

    private fun fetchTotalReminder() {
        if (BusinessContext.getAppConfigInfo().app_badge_type.contains("apiBadge")) {
            val params = HashMap<String, String>()
            BusinessContext.api?.post("i/badge/getBadge", params, object : BaseModelCallback2<BadgerResponse>((BadgerResponse::class.java)) {
                override fun onSuccess(modelResponse: BadgerResponse?, call: Call?, response: Response?) {
                    e("MainActivity2", "#fetchTotalReminder")
                    modelResponse?.let {
                        e("MainActivity2", "#fetchTotalReminder, badge=${it.data?.badge ?: 0}")
                        AppBadgerManager(this@MainBaseActivity).showAppBadger(it.data?.badge ?: 0)
                    }
                }
            })
        }
    }

    //注册tab类型,后续完成模块化改造后,应该放到各自模块的初始化中
    private fun regTabFragmentType() {
        TabFragmentManager.register("webviewTab", CordovaWebViewFragment::class.java)
        CordovaWebViewFragment.init()
    }

    protected var tabItemList = ArrayList<TabItem>()

    /* 读取json配置文件,并添加tab */
    protected open fun addTabItems() {
        //todo 优化逻辑不要删除重建，会有大量UI重新渲染
        mMainBottom?.removeAllViews()
        regTabFragmentType()
        //从json配置文件中获取tab配置列表
        tabItemList = TabUtils.getTabItemsFromConfig()
        if (useUi3()) {
            tabItemList.forEach {
                //ui3 弃用isNavbarVisible
                it.isNavbarVisible = false
                //ui3 状态栏始终显示
                it.isStatusBarVisible = true
            }
        }
        val illItemList = ArrayList<TabItem>()
        tabItemList.forEachIndexed(fun(_, tabItem) {
            val fragmentItem: TabFragmentManager.FragmentItem? = TabFragmentManager.getItemByMark(tabItem.identify)
            if (fragmentItem != null) {
                val fragmentClass: Class<*> = fragmentItem.fragmentClass
                val tabIconId: Int = getImageIdByName(this, tabItem.icon)
                val tabIconPressedId: Int = getImageIdByName(this, tabItem.iconPressed)
                val topRightIconId: Int = getImageIdByName(this, tabItem.topRightBtnIcon)
                val isNavbarVisible: Boolean = tabItem.isNavbarVisible
                val isStatusBarVisible: Boolean = tabItem.isStatusBarVisible
                val useTabBackcolor: Boolean = tabItem.useTabBackcolor
                var textColor = 0
                var textColorPressed = 0
                try {
                    if (!tabItem.textColor.isNullOrEmpty()) {
                        textColor = Color.parseColor(tabItem.textColor)
                    }
                    if (!tabItem.textColorPressed.isNullOrEmpty()) {
                        textColorPressed = Color.parseColor(tabItem.textColorPressed)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                var getNewInstance: Method? = null
                var fragmentInstance: androidx.fragment.app.Fragment? = null
                try {
                    getNewInstance = fragmentClass.getMethod("getNewInstance", JSONObject::class.java)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                fragmentInstance = if (getNewInstance != null) {
                    getNewInstance.invoke(null, if (tabItem.params == null) JSONObject() else tabItem.params!!) as androidx.fragment.app.Fragment
                } else {
                    fragmentClass.newInstance() as androidx.fragment.app.Fragment
                }
                addTabItem(fragmentInstance, tabItem.text, textColor, textColorPressed, tabIconId, tabIconPressedId, useTabBackcolor, isStatusBarVisible, isNavbarVisible, topRightIconId, tabItem, fragmentItem.mark)
            } else {//挑出非法tab项
                illItemList.add(tabItem)
            }
        })
        //去除非法的tab项
        illItemList.forEach {
            tabItemList.remove(it)
        }
        //如果只有一个tab,隐藏tab栏
        if (tabItemList.size <= 1) {
            mBottomLayoutMustGone = true
            binding.mainLayoutBottom.layoutBottom.visibility = View.GONE
            binding.ui3TabBar.visibility = View.GONE
        }
        binding.mainViewpager.adapter?.notifyDataSetChanged()

    }


    override fun onConfigurationChanged(newConfig: Configuration) {
        getResources()
        super.onConfigurationChanged(newConfig)
        if (this.checkLandscape()) {
            onConfigurationChangedLandscape()
        } else {
            onConfigurationChangedPortrait()
        }
    }

    private fun onConfigurationChangedPortrait() {
        binding.mainRightFragmentContainer.visibility = View.GONE
        binding.mainRightFragmentContainer.visibility = View.VISIBLE
        binding.mainLeftContainer.layoutParams = binding.mainLeftContainer.layoutParams.apply {
            width = RelativeLayout.LayoutParams.MATCH_PARENT
        }
    }

    private fun onConfigurationChangedLandscape() {
        binding.mainRightFragmentContainer.visibility = View.VISIBLE
        binding.mainLeftContainer.layoutParams = binding.mainLeftContainer.layoutParams.apply {
            width = resources.getDimension(R.dimen.home_width_landscape).toInt()
        }
    }


    /* 通过图片名称获取对应的图片资源id */
    protected fun getImageIdByName(context: Context, imageName: String?): Int {
        if (imageName.isNullOrEmpty()) {
            return 0
        }
        return context.resources.getIdentifier(imageName, "drawable", context.packageName)
    }

    private fun startCreateGroup() {
        BusinessContext.contact.startCreateGroup(this, emptyArray(), null, ContactChooseCallback(this))
    }

    class ContactChooseCallback(mainBaseActivity: MainBaseActivity) : IContactChooseCallback {
        private var mainActivity by weakReference(mainBaseActivity)
        override fun onSuccess(chooseContactActivity: Activity, imids: ArrayList<String>, users: ArrayList<IContactProvider.UserInfo>) {
            if (users.size == 1) {
                val bean = users[0]
                BusinessContext.im?.startPrivateChatByImid(chooseContactActivity, bean.imid!!, bean.name)
                chooseContactActivity.finish()
                return
            }
            val userImid = BusinessContext.user!!.getImid()
            imids.add(userImid!!)
            mainActivity?.let {
                it.loadingShow()
                BusinessContext.im?.joinGroup(null, null, imids, JoinGroupDataCallback(it, chooseContactActivity))
            }
        }
    }

    class JoinGroupDataCallback(mainActivity: MainBaseActivity, private val chooseContactActivity: Activity) : ICallback<JoinGroupData>(JoinGroupData::class.java) {
        private var mainActivity by weakReference(mainActivity)
        override fun onSuccess(data: JoinGroupData) {
            super.onSuccess()
            mainActivity?.loadingDismiss()
            chooseContactActivity.finish()
            BusinessContext.im?.startGroupChat(chooseContactActivity, data.id, data.name!!)
        }

        override fun onError() {
            super.onError()
            mainActivity?.loadingDismiss()
            AppUtils.showApiErrorToast()
        }
    }

    private fun loadingDismiss() {
        LoadDialog.dismiss(MyActivityManager.getInstance().currentActivity)
    }

    private fun loadingShow() {
        LoadDialog.show(MyActivityManager.getInstance().currentActivity)
    }


    override fun onPause() {
        super.onPause()
        ActivityCycleManager.onPause(CYCLE_GROUP, this)
    }

    /* 设置默认首页 */
    private fun setDefaultViewPager(index: Int, firstTime: Boolean = false) {
        var mindex = index
        //判断index合法性,防止数组越界
        if (index >= mTabItems.size) {
            mindex = 0
        }
        binding.mainViewpager.setCurrentItem(mindex, false)

        //fix ViewPager first time  setCurrentItem(0) not call onPageSelected
        if (firstTime && mindex == 0) {
            this.onPageSelected(0)
        }
    }

    /* 恢复所有tab */
    private fun resetTabItems() {
        var textColor = resources.getColor(R.color.tab_text_color)
        mTabItems.map {
            if (it.textColor != 0) {
                textColor = it.textColor
            }
            it.textView!!.setTextColor(textColor)
            it.imageView!!.setImageResource(it.res_tab_icon)
            if (CommonTheme.isLinearGradient()) {
                it.container.background = CommonTheme.getBottomLinearGradient()
            } else {
                it.container.background = null
                it.container.setBackgroundColor(Color.parseColor("#00000000"))//背景设置成透明
            }
        }
    }

    private fun tabItemClick(holder: TabItemViewHolder?) {
        if (holder == null) {
            return
        }
        currentTabItem = holder
        //设置tab文字颜色
        if (holder.textColorPressed != 0) {
            holder.textView?.apply {
                setTextColor(holder.textColorPressed)
                typeface = Typeface.DEFAULT_BOLD
            }
        } else {
            holder.textView?.apply {
                setTextColor(themeColor)
                typeface = Typeface.DEFAULT
            }
        }
        //更换图标,并将图片颜色改成和主题一致
        if (BuildConfigUtil.getBoolean("useTabColorFilter")) {
            try {
                holder.imageView!!.setImageDrawable(SkxDrawableHelper.tintDrawable(ContextCompat.getDrawable(this, holder.res_tab_icon_pressed)!!, themeColor))
            } catch (e: Exception) {
                e("MainActivity2", "${e.message}", e)
            }
            if (this.useColorFilter) holder.imageView!!.setColorFilter(themeColor)
        } else {
            //如果开启tab背景颜色,那不做图标染色
            holder.imageView!!.setImageResource(holder.res_tab_icon_pressed)
        }
        //设置tab背景色
        if (holder.useTabBackcolor) {
            holder.container.setBackgroundColor(themeColor)
        }
        //设置导航栏的标题
        actionbar_center_title?.text = holder.title
        if (useThemeWhite()) {
            actionbar_center_title?.setTextColor(resources.getColor(R.color.title_bar_text_color_dark))
        }
        if (isUi2()) {
            binding.mainLayoutTop.commonTopBottomSplit.visibility = View.GONE
        }

        if (CommonContext.getCommonCheckApiCallback().isUseUIVersion2) {
            val params = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            params.addRule(RelativeLayout.ALIGN_LEFT)
            params.addRule(RelativeLayout.CENTER_VERTICAL)
            params.leftMargin = resources.getDimension(R.dimen.toplayout_margin_15).toInt()
            actionbar_center_title?.layoutParams = params
        }

        //设置导航栏右上角按钮图标
        if (holder.main_rightBtn_icon > 0) {
            actionbar_right_img?.setImageResource(holder.main_rightBtn_icon)
            actionbar_right_img?.visibility = View.VISIBLE
            val isConversationListTabFragment = try {
                (holder.fragment as? ITabFragment)?.isConversationListTabFragment ?: false
            } catch (e: AbstractMethodError) {
                false
            }
            showMeetingBtn(isConversationListTabFragment)
            showContactBtn(isConversationListTabFragment)
        } else {
            actionbar_right_img?.visibility = View.GONE
            showMeetingBtn(false)
            showContactBtn(false)
        }
        if (useThemeWhite()) {
            actionbar_right_img?.setColorFilter(resources.getColor(R.color.title_bar_filter_color_dark), PorterDuff.Mode.MULTIPLY)
            actionbar_main_right_contact?.setColorFilter(resources.getColor(R.color.title_bar_filter_color_dark), PorterDuff.Mode.MULTIPLY)
            actionbar_main_right_meeting?.setColorFilter(resources.getColor(R.color.title_bar_filter_color_dark), PorterDuff.Mode.MULTIPLY)
        }
        //设置右上角按钮事件
        actionbar_right_img?.setOnClickListener {
            if (holder.fragment != null && holder.fragment is ITabFragment) {
                if ((holder.fragment as ITabFragment).onClickActionBarRight(it)) {
                    return@setOnClickListener
                }
            }
            getMenuPopupWindow()
        }
        setNavbarVisible(holder.isNavbarVisible)
        val tabFragment = holder.fragment as ITabFragment?
        try {
            tabFragment?.commonTopView?.apply {
                visibility = if (holder.isTitleBarVisible) View.VISIBLE else View.GONE
                setCenterTitle(holder.title ?: "")
                actionbar_right_img?.apply {
                    if (holder.main_rightBtn_icon > 0) {
                        visibility = View.VISIBLE
                        setImageResource(holder.main_rightBtn_icon)

                        setOnClickListener {
                            if (!(tabFragment.onClickActionBarRight(it))) {
                                getMenuPopupWindow()
                            }
                        }
                    } else {
                        visibility = View.GONE
                    }
                }
                if (useThemeWhite()) {
                    actionbar_right_img?.setColorFilter(resources.getColor(R.color.title_bar_filter_color_dark), PorterDuff.Mode.MULTIPLY)
                    actionbar_main_right_contact?.setColorFilter(resources.getColor(R.color.title_bar_filter_color_dark), PorterDuff.Mode.MULTIPLY)
                    actionbar_main_right_meeting?.setColorFilter(resources.getColor(R.color.title_bar_filter_color_dark), PorterDuff.Mode.MULTIPLY)
                }
            }
        } catch (e: AbstractMethodError) {
            e(TAG, e.message ?: "", e)
        }
        setLayoutStatusBarVisible(true)//状态栏先显示,再修改,防止有时候修改不了
        setLayoutStatusBarVisible(holder.isStatusBarVisible)
    }

    private fun initMenuPopupWindow(popupView: View, popupWindow: PopupWindow) {
        val searchSubscribeService: TextView? = popupView.findViewById(R.id.search_subscribe_service)
        val line: View? = popupView.findViewById(R.id.line_search_subscribe_service)
        if (BuildConfigUtil.getBoolean("useSubscribeService", false)
            && BusinessContext.getAppConfigInfo().isSubscribe_number) {
            searchSubscribeService?.visibility = View.VISIBLE
            line?.visibility = View.VISIBLE
            searchSubscribeService?.setOnClickListener {
                popupWindow.dismiss()
                this@MainBaseActivity.start("subscribe_service_search")
            }
        } else {
            searchSubscribeService?.visibility = View.GONE
            line?.visibility = View.GONE
        }
    }

    private fun getFragmentByMark(mark: String): androidx.fragment.app.Fragment? {
        if (mark.isNullOrEmpty()) {
            return null
        }
        for (tabItem in mTabItems) {
            if (tabItem.mark.equals(mark)) {
                return tabItem.fragment
            }
        }
        return null
    }

    private fun addTabItem(
        fragment: androidx.fragment.app.Fragment, title: String, textColor: Int, textColorPressed: Int,
        @DrawableRes tab_icon: Int, @DrawableRes tab_icon_pressed: Int, useTabBackcolor: Boolean,
        isStatusBarVisible: Boolean, isNavbarVisible: Boolean, @DrawableRes rightBtnIcon: Int,
        tabItemConfig: TabItem? = null,
        tabMark: String = ""
    ) {
        this.mFragment.add(fragment)

        val tabItem = layoutInflater.inflate(if (BuildConfigUtil.getBoolean("style_bjsw", false)) R.layout.layout_bottom_item_horizontal else R.layout.layout_bottom_item, mMainBottom, false)
        mMainBottom?.addView(tabItem)
        val holder = TabItemViewHolder(tabItem, tabItemConfig)
        mTabItems.add(holder)
        //tab数量角标
        (fragment as? ITabFragment)?.apply {
            setOnCountChangeListener(object : IOnCountChangeListener {
                override fun onCountChange(count: Int) {
                    updateCount(holder, count)
                }
            })
            setDragPointView(holder.dragPointView)
        }
        (fragment as? ITabFragment2)?.tabItem = tabItemConfig
        holder.fragment = fragment
        holder.mark = tabMark
        holder.res_tab_icon = tab_icon
        holder.res_tab_icon_pressed = tab_icon_pressed
        holder.main_rightBtn_icon = rightBtnIcon
        holder.title = title
        holder.textColor = textColor
        holder.textColorPressed = textColorPressed
        holder.imageView!!.setImageResource(holder.res_tab_icon)
        holder.textView!!.text = holder.title
        holder.useTabBackcolor = useTabBackcolor
        holder.isStatusBarVisible = isStatusBarVisible
        holder.isNavbarVisible = isNavbarVisible
        if (holder.textColorPressed != 0) {
            holder.textView!!.setTextColor(holder.textColor)
        }
        //设置tab点击事件
        holder.rootView.setOnClickListener {
            this.mViewPager?.setCurrentItem(mFragment.indexOf(fragment), false)
        }
    }

    private fun initMainViewPager() {
        //临时存储所有tabItem

        //临时存储所有tabItem
        val childCount = mMainBottom?.childCount
        val map: List<View> = java.util.ArrayList()
//        for (int i = 0; i < childCount; i++) {
//            View tabItem = mMainBottom.getChildAt(i);
//            map.add(tabItem);
//        }
        //        for (int i = 0; i < childCount; i++) {
//            View tabItem = mMainBottom.getChildAt(i);
//            map.add(tabItem);
//        }
        mMainBottom?.removeAllViews()
        mViewPager = findViewById(R.id.main_viewpager)
        (mViewPager as SwappableViewPager?)?.apply {
            pageSwappable = BuildConfigUtil.getBoolean("main_tab_swappable", false)
            if (useUi3()) {
                setPageTransformer(false, null)
            }
        }
    }

    protected open fun updateCount(holder: TabItemViewHolder, count: Int) {
        /*Android O必须显示调用*/
        runOnUiThread {
            val mUnreadNumView = holder.dragPointView
            if (mUnreadNumView != null) {
                if (count == 0) {
                    mUnreadNumView.visibility = View.GONE
                } else if (count in 1..9999) {
                    mUnreadNumView.visibility = View.VISIBLE
                    mUnreadNumView.text = "$count"
                } else {
                    mUnreadNumView.visibility = View.VISIBLE
                    mUnreadNumView.setText(R.string.no_read_message)
                }
            }
        }
    }

    override fun addTab(fragment: androidx.fragment.app.Fragment, title: String, icon: Int, tab_icon_pressed: Int, main_action_add_converstion: Int, id: String?) {
        addTabItem(fragment, title, 0, 0, icon, tab_icon_pressed, useTabBackcolor = false, isStatusBarVisible = true, isNavbarVisible = true, rightBtnIcon = main_action_add_converstion)
    }

    override fun getResources(): Resources {
        val res = super.getResources()
        if (!BuildConfigUtil.getBoolean("forcedFontScale", false)) {
            return res
        }
        val newConfig = Configuration()
        newConfig.setToDefaults()
        res.updateConfiguration(newConfig, res.displayMetrics)
        return res
    }

    override fun onResume() {
        super.onResume()
        //Fragment fragment = mFragment.get(currrntFg);
        //Fragment fragment = mFragment.get(currrntFg);
        if (CommonContext.getComonCheckApiCallback().useTheme()) {
            val color_ = ThemeM.themeColor
            if (!useUi3()) {
                //ui3不需要在resume设置状态栏颜色
                setHeaderBg(color_)
            }
            val buttonDrawable = resources.getDrawable(com.fingersoft.im.common.R.drawable.switchbutton_on)
            DrawableCompat.setTint(buttonDrawable, color_)
        }

        for (cycle in main_cycles) {
            cycle.onResume(this)
        }

//        onAddressBookSyncStatusChanged();

//        onAddressBookSyncStatusChanged();
        EventBus.getDefault().post(EventManager.OnRNcancelHiddenTabBar())

        if (AppUtils.isLogged() && getAppConfigInfo(this).isSensitive_word) {
            val params: MutableMap<String, String> = HashMap()
            val listsize = SensitiveWordDaoUtils.instance.getAllSensitiveWord()!!.size
            if (listsize == 0) {
                params["timestamp"] = "0"
            } else {
                params["timestamp"] = com.fingersoft.feature.sensitiveword.dao.AppUtils.getSensitiveTime().toString()
            }
            val gson = Gson()
            val jsonStr = gson.toJson(params)
            SensitiveWordContext.instance.getSensitiveWord(this, "i/im/sensitiveword/query.token", jsonStr, object : ICallback<Any?>() {
                override fun onError() {
                    onError("未知错误")
                }

                override fun onError(errMsg: String?) {
                    e(TAG, "getSensitiveWord error:${errMsg ?: "未知错误"}")
                }
            })
        }
        if (currentTabItem != null) {//恢复tab和状态栏显示
            tabItemClick(currentTabItem)
        }
        ActivityCycleManager.onResume(CYCLE_GROUP, this)
        if (!IntentQueue.default.isEmpty()) {
            val intent = IntentQueue.default.poll() ?: Intent()
            if(intent.hasExtra("activity")) {
                val newIntent = Intent(this, intent.extras!!.getSerializable("activity") as? Class<*>)
                newIntent.putExtras(intent.extras!!)
                this.startActivity(newIntent)
            }
        }
        EventBus.getDefault().post(EventManager.OnMainActivityResume())
    }

    override fun onDestroy() {
        BusinessContext.tabHost = null
        super.onDestroy()
        for (cycle in main_cycles) {
            cycle.onDestroy(this)
        }
        ActivityCycleManager.onDestroy(CYCLE_GROUP, this)
        NavigationHostManager.hosts.remove(navigationHost)
    }

    override fun onBackPressed() {
        val handled = false
        LogUtils.d("handled=$handled")
        if (checkLandscape() && navigationHost.popBackStack()) {
            return
        }
        if (mIsAtHome) {
            confirmExitApp()
            //断开vpn
            if(BuildConfigUtil.getBoolean("vpnCloseWhenExit",false)) {
                BusinessContext.mVPNProvider?.cleanVPNAccount()
            }
        }
    }

    companion object {
        protected const val CYCLE_GROUP = "MainActivity"
        var TAG = "MainActivity"


        fun startConversation(context: Context) {
            val intent = Intent(context, MainActivity2::class.java)
            intent.putExtra("uifrom", 0)
            intent.putExtra("selected", "conversation")
            context.startActivity(intent)
        }

        fun startSystemConversation(activity: Activity) {
            val intent = Intent(activity, MainActivity2::class.java)
            intent.putExtra("systemconversation", true)
            activity.startActivity(intent)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(event: EventManager.OnApiBadge) {
        fetchTotalReminder()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(event: ThemeChangedEvent) {
        onResume()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(event: EventManager.OnRNLogout) {
        MyStompClient.disconnect()
        event.userId = AppUtils.getUser().userId

        for (cycle in main_cycles) {
            cycle.onEvent(this, event)
        }
        AppUtils.logout(this)
        finish()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(event: EventManager.OnLogout) {
        BusinessContext.login!!.logout()
        MyStompClient.disconnect()
        finish()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(event: EventManager.OnRNkickedOfflineByOtherClient) {
        main_cycles.forEach { cycle -> cycle.onEvent(this, event) }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(event: PluginsEventManager.OnLocateSuccess) {
        val res = event.result as JSONObject
        try {
            if (MyStompClient.mStompClient != null) {
                MyStompClient.send(JSONUtils.toJsonString(AppLaunch(this, res.getDouble("longitude"), res.getDouble("latitude"))))
            }
        } catch (e: JSONException) {
            e.printStackTrace()
        }

    }

    @SuppressLint("RestrictedApi")
    protected fun initViews() {
        actionbar_right_img = findViewById(R.id.actionbar_main_right_img)
        actionbar_main_right_contact = findViewById(R.id.actionbar_main_right_contact)
        actionbar_main_right_meeting = findViewById(R.id.actionbar_main_right_meeting)
        actionbar_center_title = findViewById(R.id.actionbar_main_center_title)

        //右上角下拉菜单
        mCustomMenuView = PopupMenuView(this, R.layout.layout_custom_menu)
        mCustomMenuView?.inflate(R.menu.menu_pop, MenuBuilder(this))
        mCustomMenuView?.orientation = LinearLayout.VERTICAL
        mCustomMenuView?.setOnMenuClickListener(this)
        mLayoutStatusBar = this.createStatusBarView(R.id.main_status_bar)

        // 由于主页沉浸，状态栏需要动态显示。
        mLayoutStatusBar = findViewById(R.id.main_status_bar)
        mLayoutMainContent = findViewById(R.id.main_content)
        //        // 初始化状态栏填充高度
        //        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mLayoutStatusBar.getLayoutParams();
        //        params.height = getStatusBarHeight(this);
        //        mLayoutStatusBar.setLayoutParams(params);

        showMeetingBtn(true)
        showContactBtn(true)
    }

    private fun showMeetingBtn(autoCheck: Boolean) {
        if (!autoCheck) {
            actionbar_main_right_meeting?.visibility = View.GONE
            return
        }
        actionbar_main_right_meeting?.visibility = if (((BusinessContext.getAppConfigInfo().isMeetingOnlineEnabled
                && BuildConfigUtil.getBoolean("useOnlineConference"))
                && BuildConfigUtil.getBoolean("useOnlineConferenceInIMMenu")))
            View.VISIBLE
        else
            View.GONE
        actionbar_main_right_meeting?.setOnClickListener(this)
    }

    private fun showContactBtn(autoCheck: Boolean) {
        if (!autoCheck) {
            actionbar_main_right_contact?.visibility = View.GONE
            return
        }
        actionbar_main_right_contact?.visibility = if (BuildConfigUtil.getBoolean("style_bjsw")) View.VISIBLE else View.GONE
        actionbar_main_right_contact?.setOnClickListener(this)

    }

    private fun setNavbarVisible(b: Boolean) {
        binding.mainLayoutTop.layoutTop.visibility = if (b) View.VISIBLE else View.GONE
    }

    private fun setLayoutStatusBarVisible(isVisible: Boolean) {
        // 仅4.4及以上才需要处理
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (isVisible) {
                // 初始化状态栏填充高度
                val lparams = mLayoutStatusBar?.layoutParams as RelativeLayout.LayoutParams
                lparams.height = (this).getStatusBarHeight()
                mLayoutStatusBar?.layoutParams = lparams
                // 显示自制状态栏
                mLayoutStatusBar?.visibility = View.VISIBLE

                // 改变布局
                val params = mLayoutMainContent?.layoutParams as RelativeLayout.LayoutParams?
                if (params == null) {
                    w(TAG, "setLayoutStatusBarVisible:params is null")
                } else {
                    params.removeRule(RelativeLayout.ALIGN_PARENT_TOP)
                    params.addRule(RelativeLayout.BELOW, R.id.main_status_bar)
                    mLayoutMainContent?.layoutParams = params
                }
                if (!useUi3()) {
                    setStatusBarColor(resources.getColor(android.R.color.transparent))
                }
            } else {
                // 隐藏自制状态栏
                mLayoutStatusBar?.visibility = View.GONE

                // 改变布局
                val params = mLayoutMainContent?.layoutParams as RelativeLayout.LayoutParams?
                if (params == null) {
                    w(TAG, "setLayoutStatusBarVisible:params is null")
                } else {
                    params.removeRule(RelativeLayout.BELOW)
                    params.addRule(RelativeLayout.ALIGN_PARENT_TOP)
                    params.height = 0
                    mLayoutMainContent?.layoutParams = params
                }
            }
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.actionbar_main_right_meeting -> start("cn.rongcloud.rce.ui.call.CallActivity")
            R.id.actionbar_main_right_contact -> BusinessContext.contact.openContactActivity(this)
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        parseScheme(intent)
    }

    private fun parseScheme(intent: Intent) {
        val schemaUri = intent.data
        Log.i(TAG, "parseScheme:data=${intent.data},tag=${intent.extras}")
        if (schemaUri != null) {//从schema跳转
            val path = schemaUri.path ?: ""
            Log.i(TAG, "parseScheme path=${path}")
            if (path.contains("conversationlist")) {//即时消息跳转,需要切换到消息的tab
                Log.i(TAG, "conversationlist")
                val fragment = getFragmentByMark("messageTab")
                if (fragment != null) {
                    defaultTabId = mFragment.indexOf(fragment)
                    Log.i(TAG, "conversationlist defaultTabId=${defaultTabId}")
                    Handler().postDelayed({
                        //延时设置,否则状态栏没法生效
                        setDefaultViewPager(defaultTabId, true)
                    }, 200)
                } else {
                    Log.i(TAG, "conversationlist defaultTabId=null")
                }
                // 华为推送跳转会话页面
                if (intent.data?.getBooleanQueryParameter("isFromPush", false) == true) {
                    try {
                        val options = intent.extras?.getString("options") ?: "{}"
                        val jsonObject = JSONObject(options)
                        val rc = JSONObject(jsonObject.getString("rc"))
                        val conversationType = rc.getInt("conversationType") // 会话类型
                        val targetId = rc.getString("targetId") // 目标 targetId
                        BusinessContext.im?.startConversationRaw(this, conversationType, targetId, "")
                    } catch (e: Exception) {
                        Log.e(TAG, "华为推送跳转会话页面 error:${e.message}", e)
                    }
                }
            } else if (path.contains("/tab/personal")) {
                val fragment = getFragmentByMark("settingTab")
                if (fragment != null) {
                    defaultTabId = mFragment.indexOf(fragment)
                    Handler().postDelayed({
                        //延时设置,否则状态栏没法生效
                        setDefaultViewPager(defaultTabId, true)
                    }, 200)
                }
            }
        }
    }

    private fun confirmExitApp() {
        if (BuildConfigUtil.getBoolean("enableSingleBackpress2Home", false)
            || BuildConfigUtil.getBoolean("appWidgetBack2Source", false)) {
            back2Home()
            return
        }
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            ToastUtils.show(getString(R.string.double_click_exit_app))
            mExitTime = System.currentTimeMillis()
        } else {
            finish()
        }
    }
    private fun back2Home() {
        val home =  Intent(Intent.ACTION_MAIN)
        home.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
        home.addCategory(Intent.CATEGORY_HOME)
        startActivity(home)
    }
    /**
     * // TODO: 2019-06-21 优化日志使用异步
     */
    private fun eventLogAddAndUpload() {
        //记录启动事件
        AppEventUtil.writeLandingState(AppEventType.AppLaunch, this)
        //上传appevent.log文件
        com.fingersoft.feature.personal.api.ApiUtils.UploadAppEventLog(this, object : ICallback<Any?>() {
            override fun onSuccess(data: Any?) {
                AppEventUtil.delete()
            }

            override fun onError() {

            }
        })
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
        // 防止按menu键tab下滑
        if (keyCode == KeyEvent.KEYCODE_MENU && !AppUtils.DEBUG) {
            return true
        }
        return super.onKeyUp(keyCode, event)
    }

    private fun getMenuPopupWindow() {
        if (BusinessContext.contact.checkAndShowSyncingDialog(this)) {
            return
        }

        val popupView = if (BuildConfigUtil.getBoolean("useThemeWhite", false)) layoutInflater.inflate(R.layout.meeting_menu_bar_light, null)
        else layoutInflater.inflate(R.layout.meeting_menu_bar, null)

        val mPopupWindow = PopupWindow(popupView)
        mPopupWindow.width = ViewGroup.LayoutParams.WRAP_CONTENT
        mPopupWindow.height = ViewGroup.LayoutParams.WRAP_CONTENT
        mPopupWindow.isTouchable = true
        mPopupWindow.isOutsideTouchable = true
        mPopupWindow.isClippingEnabled = false
        val groupChat = popupView.findViewById<TextView>(R.id.groupChat)
        val meeting = popupView.findViewById<TextView>(R.id.meeting)
        val scan = popupView.findViewById<TextView>(R.id.scan)
        //        ImageView overlay = popupView.findViewById(R.id.overlay);
        val mLine = popupView.findViewById<View>(R.id.mLine)
        mPopupWindow.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        mPopupWindow.isOutsideTouchable = true
        mPopupWindow.isFocusable = true
        //        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
        //            @Override
        //            public void onDismiss() {
        //                setWindowLight();
        //            }
        //        });
        if (useGnet() && useGnetInIMMenu()) {
            val layoutParams = mLine.layoutParams as LinearLayout.LayoutParams
            layoutParams.weight = popupView.measuredWidth.toFloat()
            mLine.layoutParams = layoutParams
            meeting.visibility = View.VISIBLE
            mLine.visibility = View.VISIBLE
            meeting.setOnClickListener { v ->
                mPopupWindow.dismiss()
                if (Build.VERSION.SDK_INT >= 23) {
                    if (((ActivityCompat.checkSelfPermission(mContext!!, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext!!, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) || (ActivityCompat.checkSelfPermission(mContext!!, android.Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext!!, android.Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED))) {
                        ToastUtils.show("缺少权限无法使用该功能")
                        return@setOnClickListener
                    }
                }
                val list = ArrayList<String>()
                BusinessContext.conference!!.createConference(this, list)
            }
        }
        //        mPopupWindow.showAtLocation(moreImage, Gravity.RIGHT | Gravity.TOP, 0, 0);
        //
        //        overlay.setOnClickListener(new View.OnClickListener() {
        //            @Override
        //            public void onClick(View v) {
        //                mPopupWindow.dismiss();
        //            }
        //        });
        groupChat.setOnClickListener { v ->
            mPopupWindow.dismiss()
            startCreateGroup()
        }

        scan.setOnClickListener { view ->
            mPopupWindow.dismiss()
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                PermissionsUtils.grantCameraPeromissions(this, PermissionsUtils.PERMISSION_CAMERA_CODE, object : PermissionsUtils.RequestPermissionsCallBack {
                    override fun onRequest() {

                    }

                    override fun onRefused() {

                    }

                    override fun onGranted() {
                        CustomCaptureActivity.start(this@MainBaseActivity)
                    }
                })
            } else {
                CustomCaptureActivity.start(this)
            }

        }

        if (BuildConfigUtil.getBoolean("style_bjsw", false)) {
            scan.visibility = View.GONE
        } else {
            scan.visibility = View.VISIBLE
        }

        initMenuPopupWindow(popupView, mPopupWindow)
        val w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        val h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        popupView.measure(w, h)
        if (actionbar_right_img != null) {
            mPopupWindow.showAsDropDown(actionbar_right_img, -(popupView.measuredWidth - actionbar_right_img!!.width), 0)
            setWindowAlpha(0.5f)
        }

        mPopupWindow.setOnDismissListener {
            setWindowAlpha(1f)
        }
    }

    private fun setWindowAlpha(value: Float) {
        if (useThemeWhite()) {
            val lp: WindowManager.LayoutParams = window.attributes
            lp.alpha = value
            window.attributes = lp
        }
    }

    override fun onOptionMenuClick(position: Int, menu: OptionMenu): Boolean {
        when (menu.id) {
            R.id.pop_menu_item_quliao -> startCreateGroup()
            R.id.pop_menu_item_huiyi -> {
                val alertDialog = AlertDialog.Builder(this).setTitle("温馨提示")
                    .setMessage("功能开发中！")
                    .create()
                alertDialog.show()
            }
        }
        return true
    }

    private fun setHeaderBg(color: Int) {
        themeColor = color
        if ("" != BuildConfigUtil.getString("common_status_bar_start_color", "")) {
            if (BuildConfigUtil.getBoolean("style_bjsw", false)) {
                var statusBarColor = BuildConfigUtil.getString("common_status_bar_color", "#0000000")
                if (TextUtils.isEmpty(statusBarColor)) {
                    statusBarColor = "#000000"
                }
                mLayoutStatusBar?.setBackgroundColor(
                    Color.parseColor(statusBarColor)
                )
            }
            binding.mainLayoutTop.layoutTop.background = CommonTheme.drawableLinearGradient()
        } else {
            val backgroundColor = if (useThemeWhite()) Color.parseColor("#ffffff") else color
            binding.mainLayoutTop.layoutTop.background = ImageUtils.getImageBackground(0, backgroundColor)
            mLayoutStatusBar?.background = ImageUtils.getImageBackground(0, backgroundColor)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(event: HomeTabSwitchEvent) {
        mTabItems.find { it.tabItemConfig?.id == event.id }?.let {
            this.mViewPager?.setCurrentItem(mFragment.indexOf(it.fragment), false)
        }
    }

}

fun useThemeWhite() = BuildConfigUtil.getBoolean("useThemeWhite", false)

fun isUi2() = BuildConfigUtil.getString("setUIVersion", "ui1") == "ui2"

fun startMainActivity(context: Context, from: Int = 0, checkLock: Boolean = true) {
    val intent = Intent(context, MainActivity2::class.java)
    intent.putExtra("uifrom", from)
    intent.putExtra("checkLock", checkLock)
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    context.startActivity(intent)
}

fun useUi3() = BuildConfigUtil.getBoolean("useUi3", false)

/**
 * ui3
 * */
class MainActivity2 : MainBaseActivity() {

    private var tabItemMap = mutableListOf<Pair<UITabBar.Item, TabItem>>()
    override fun onCreate(savedInstanceState: Bundle?) {
        if (useUi3()) {
            setTheme(R.style.ui_AppTheme)
        }
        super.onCreate(savedInstanceState)
        if (useUi3()) {
            binding.mainLayoutBottom.layoutBottom.visibility = View.GONE
            binding.ui3TabBar.apply {
                visibility = View.VISIBLE
                onItemClickListener = View.OnClickListener {
                    val item = it.tag as? UITabBar.Item
                    val index = tabItemMap.indexOfFirst { it.first.title == item?.title }
                    binding.ui3TabBar.selectedIndex = index
                    mViewPager?.currentItem = index
                }
                selectedIndex = tabItemList.indexOfFirst { it.isHomeDefault }
            }
        }
    }

    override fun setContentView(layoutResID: Int) {
        super.setContentView(layoutResID)
        if (useUi3()) {
            (window.decorView as ViewGroup).addView(UIStatusBar(this).apply { visibility = View.GONE })
        }
    }

    override fun addTabItems() {
        super.addTabItems()
        if (useUi3()) {
            tabItemMap.clear()
            tabItemMap.addAll(tabItemList.map { Pair(UITabBar.Item(it.text, getImageIdByName(this, it.icon)), it) })
            binding.ui3TabBar.items = tabItemMap.map { it.first }
        }
    }

    override fun updateCount(holder: TabItemViewHolder, count: Int) {
        super.updateCount(holder, count)
        val title = holder.title
        updateTabItemBadge(title, count)
    }

    private fun updateTabItemBadge(title: String?, count: Int) {
        binding.ui3TabBar.items = tabItemMap.map {
            if (it.first.title == title) {
                UITabBar.Item(it.first.title, it.first.iconResId, badgeNumber = count)
            } else
                it.first
        }
    }

}
